package com.doraz.orb.methods.stream;

import java.io.InputStream;
import java.util.ArrayList;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.doraz.orb.Constants;
import com.doraz.orb.methods.OrbMethod;
import com.doraz.orb.structs.OrbObject;
import com.doraz.orb.utils.XMLUtils;

public class StreamURL extends OrbMethod {
	private String[] urls;
	private String[] titles;
	
	public StreamURL(String id, String name, String format) {
		super("stream", "xml/stream", Constants.RETURN_NONE);
		addParam(name, id);
		addParam("streamFormat", format);
	}
	
	@Override
	public OrbObject parseResponse(InputStream in) {
		Document doc = XMLUtils.getDocument(in);
		ArrayList<String> urlList = new ArrayList<String>();
		ArrayList<String> titleList = new ArrayList<String>();
		if(doc != null) {
			NodeList items = doc.getElementsByTagName("item");
			for(int i = 0; i < items.getLength(); i++) {
				Element item = (Element) items.item(i);
				urlList.add(item.getAttribute("url"));
				NodeList fields = item.getElementsByTagName("item");
				boolean foundTitle = false;
				for(int x = 0; !foundTitle && x < fields.getLength(); x++) {
					Element field = (Element) fields.item(x);
					if(field.getAttribute("name").equals("title")) {
						titleList.add(""+field.getNodeValue());
					}
				}
				
				if(!foundTitle) {
					titleList.add("(Unknown)");
				}
			}
			
			this.urls = urlList.toArray(new String[urlList.size()]);
			this.titles = titleList.toArray(new String[titleList.size()]);
		}
		
		return null;
	}
	
	
}
